package cn.xqj.org.service.impl;

import cn.xqj.basic.service.impl.BaseServiceImpl;
import cn.xqj.basic.util.MD5Utils;
import cn.xqj.basic.util.PageList;
import cn.xqj.basic.util.StrUtils;
import cn.xqj.org.domain.Employee;
import cn.xqj.org.mapper.EmployeeMapper;
import cn.xqj.org.query.EmployeeQuery;
import cn.xqj.org.service.IEmployeeService;
import cn.xqj.user.domain.Logininfo;
import cn.xqj.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void add(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        employee.setPassword(MD5Utils.encrypByMd5(employee.getPassword() + salt));
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.add(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        if (employee.getRole_id() != null) {
            employeeMapper.addEmployeeRole(employee.getId(),employee.getRole_id());
        }
        super.add(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public void del(Long id) {
        Employee employee = employeeMapper.findOne(id);
        logininfoMapper.del(employee.getLogininfo_id());
        employeeMapper.delEmployeeRoleByEid(id);
        super.del(id);
    }

    @Override
    public void update(Employee employee) {
        Long logininfo_id = employee.getLogininfo_id();
        Logininfo logininfo = logininfoMapper.findOne(employee.getLogininfo_id());
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        employeeMapper.delEmployeeRoleByEid(employee.getId());
        if (employee.getRole_id() != null) {
            employeeMapper.addEmployeeRole(employee.getId(),employee.getRole_id());
        }
        super.update(employee);
    }


    @Override
    public void patchDel(Long[] ids) {
        for (Long id : ids) {
            del(id);
        }
    }

    @Override
    public Employee findByLogininfoId(Long id) {
        return employeeMapper.findByLogininfoId(id);
    }

    @Override
    public List<Employee> list(Long shopId) {
        return employeeMapper.list(shopId);
    }
}
